import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, TreeSelect, Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { transTitle, handleReturnArray } from '@/utils/utils';
import { queryRule, updateRule, addRule, removeRule } from './service';
import FormItem from 'antd/lib/form/FormItem';
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule({
      name: fields.name,
      desc: fields.desc,
      key: fields.key,
    });
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (payload, actionRef) => {
  const hide = message.loading('正在删除');

  try {
    await removeRule(payload);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [count, setCount] = useState({});
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [menuValues, setMenuValues] = useState([]);
  const [treeValue, handleTreeValue] = useState();

  const TreeOnChange = (value) => {
    handleTreeValue(value);
  };
  useEffect(() => {
    return () => {
      setMenuValues(null);
    };
  }, []);
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '设备名称',
      dataIndex: 'name',
      valueType: 'text',
      render: (_, record) => {
        return (
          <>
            <span>{record.name}</span>
          </>
        );
      },
    },
    {
      title: '设备型号',
      dataIndex: 'sn',
      valueType: 'text',
      render: (_, record) => {
        return (
          <>
            <span>{record.sn}</span>
          </>
        );
      },
    },
    {
      title: '所属区域',
      dataIndex: 'areaString',
      valueType: 'text',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false}>
            <TreeSelect
              showSearch
              // style={{ width: '400px' }}
              value={treeValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择父级"
              allowClear
              treeDataSimpleMode
              treeData={menuValues}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onChange={TreeOnChange}
            />
          </FormItem>
        );
      },
      render: (_, record) => {
        return (
          <>
            <span>{record.areaString}</span>
          </>
        );
      },
    },
    {
      title: '所属IP',
      dataIndex: 'desc',
      valueType: 'text',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <>
            <span>{record.ip}</span>
          </>
        );
      },
    },
    {
      title: '故障时间',
      dataIndex: 'time',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '故障描述',
      dataIndex: 'text',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <Popconfirm
            placement="top"
            title="确定要删除吗?"
            onConfirm={() => {
              handleRemove(record.id, actionRef);
            }}
            okText="Yes"
            cancelText="No"
          >
            <a onClick={() => {}}>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        bordered
        toolBarRender={false}
        beforeSearchSubmit={(payload) => {
          payload.areaId = payload.areaString;
          delete payload.areaString;
          return payload;
        }}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          const { list, total } = payload;
          setCount(total);
          return list;
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
        rowSelection={false}
      />
      <CreateForm onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable
          onSubmit={async (value) => {
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
